<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container" style="display: inline-flex;">
      <el-date-picker
        v-model="timeInfo"
        value-format="yyyy-MM-dd"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
      >
        <!-- 使用expireTimeOption方法 -->
      </el-date-picker>
      <el-input
        v-model="listQuery.search"
        clearable
        class="filter-item"
        style="width: 200px;"
        placeholder="输入单号"
      />
      <el-select
        v-model="listQuery.storeOrderState"
        clearable
        style="width: 200px"
        class="filter-item"
        placeholder="请选择状态">
        <el-option v-for="(item,index) in statusMap" :key="index" :label="item.name" :value="item.value"/>
      </el-select>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >查找</el-button>
      <!-- <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >添加</el-button> -->
      <!-- <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-data-analysis"
        @click="skuSummary"
      >导出</el-button> -->
    </div>

    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      size="small"
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
      style="white-space: pre-line"
    >
      <el-table-column prop="orderNo" align="center" label="单号">
        <template slot-scope="scope">
          <el-link
            :underline="false"
            type="primary"
            @click="handleDetail(scope.row)">{{ scope.row.orderNo }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column align="center" label="退货时间">
        <template slot-scope="scope"><el-col>{{ scope.row.orderReturnFinishTime | formatGmt }}</el-col></template>
      </el-table-column>
      <el-table-column prop="orderGoodsReturnCount" align="center" label="退货数量"/>
      <el-table-column align="center" label="退货总额">
        <template slot-scope="scope"><el-col>{{ (scope.row.orderReturnAmount/100).toFixed(2) }}</el-col></template>
      </el-table-column>
      <el-table-column prop="adminRealname" align="center" label="操作人"/>
      <el-table-column prop="orderReturnState" align="center" label="状态">
        <template slot-scope="scope">
          <el-tag v-if=" scope.row.orderReturnState === 0">待审核</el-tag>
          <el-tag v-if=" scope.row.orderReturnState === 1">已通过</el-tag>
          <el-tag v-if=" scope.row.orderReturnState === 2" type="danger">驳回</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="auditAdminRealname" align="center" label="审核人"/>
      <el-table-column align="center" label="操作" width="300" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.orderReturnState =='0'"
            type="primary"
            size="mini"
            @click="handleAudit(scope.row)"
          >审核</el-button>
          <el-button
            type="primary"
            size="mini"
            @click="handleDetail(scope.row)"
          >查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.pageNo"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <!-- 审核对话框 -->
    <el-dialog
      v-loading="auditFormLoading"
      :visible.sync="auditDialogVisible"
      width="30%"
      center>
      <el-form ref="auditDataForm" :model="auditDataForm">
        <el-form-item align="center">
          <el-radio-group v-model="auditDataForm.orderState">
            <el-radio label="1" @change="changeOrderState">通过</el-radio>
            <el-radio label="2" @change="changeOrderState">驳回</el-radio>
          </el-radio-group>
        </el-form-item >
        <el-form-item v-if="auditDataForm.orderState == '2'" label="驳回理由">
          <el-input v-model="auditDataForm.auditComment" type="textarea" rows="3" placeholder=""/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="auditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="auditOrder()">确认</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改对话框 -->
    <el-dialog v-loading="optloading" :width="optDiaLogWidth" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="dataForm"
        status-icon
        label-position="left"
        label-width="100px"
        style="margin-left:60px;"
      >
        <el-form-item prop="warehouseId">
          <label slot="label">仓&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;库</label>
          <el-select v-model="dataForm.warehouseId" clearable @change="ifCanSelSpu">
            <el-option v-for="(key, index) in warehouseList" :key="index" :label="key.warehouseName" :value="key.id" />
          </el-select>
        </el-form-item>
        <el-form-item prop="supplierId">
          <label slot="label">供&nbsp;&nbsp;应&nbsp;&nbsp;商</label>
          <el-select v-model="dataForm.supplierId" clearable placeholder="请选择" @change="ifCanSelSpu">
            <el-option v-for="(key, index) in supplierList" :key="index" :label="key.supplierName" :value="key.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="单据备注" prop="orderReturnInfo">
          <el-col :span="12">
            <el-input v-model="dataForm.orderReturnInfo" type="textarea" rows="3" clearable placeholder=""/>
          </el-col>
        </el-form-item>
        <el-form-item label="退货商品" prop="purchaseStoreOrderSkus">
          <el-col :span="4"><span>已选择({{ selectSpuList.length>0?selectSpuList.length :'0' }})件商品</span></el-col>
          <el-col :span="10">
            <el-button :disabled="dataForm.warehouseIsSelected" type="primary" size="mini" @click="handleSkuAdd">选择商品</el-button>
          </el-col>
        </el-form-item>
        <el-form-item label="商品详情" prop="purchaseStoreOrderSkus">
          <el-table
            :data="selectSpuList"
            size="small"
            border
            fit
            highlight-current-row
            style="white-space: pre-line">
            <el-table-column v-if="hidden" prop="spuId"/>
            <el-table-column v-if="hidden" align="center" label="skuId" prop="skuId"/>
            <el-table-column align="center" label="商品" prop="goodsName" width="180px">
              <template slot-scope="scope">
                <el-col :span="6"><img :src="scope.row.img + '?x-oss-process=style/100px'" width="40"></el-col>
                <el-col :span="18" style="padding-top: 15px;">{{ scope.row.spuName +''+ scope.row.skuName }}</el-col>
              </template>
            </el-table-column>
            <el-table-column align="center" label="条形码" prop="barCode"/>
            <el-table-column prop="unit" align="center" label="单位"/>
            <el-table-column prop="warehouseSkuNum" align="center" label="可退数量"/>
            <el-table-column align="center" label="平均成本">
              <template slot-scope="scope">
                <el-col>{{ scope.row.averPrice.toFixed(2) }}</el-col>
              </template>
            </el-table-column>
            <el-table-column align="center" label="退货数量" prop="goodsReturnNum" width="120px">
              <template slot-scope="scope">
                <el-form ref="scope.row">
                  <el-form-item>
                    <el-input
                      v-model="scope.row.goodsReturnNum"
                      clearable
                      placeholder=""
                      @keyup.native="goodsBuyNumLimit(scope.row)"/>
                  </el-form-item>
                </el-form>
              </template>
            </el-table-column>
            <el-table-column align="center" label="退货单价" prop="goodsPrice" width="120px">
              <template slot-scope="scope">
                <el-form ref="scope.row">
                  <el-form-item>
                    <el-input v-model="scope.row.goodsPrice" placeholder=""/>
                  </el-form-item>
                </el-form>
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作">
              <template slot-scope="scope">
                <el-link :underline="false" @click="removeSpu(scope.row.skuId)"><span
                  style="color: red;">移除</span></el-link>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="退货总数" prop="orderGoodsReturnCount">
          <span>{{ selSpuListTotal }}</span>
        </el-form-item>
        <el-form-item label="退货总额" prop="orderReturnAmount">
          <span>{{ selSpuListTotalPrice }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>
    <!-- 添加商品 -->
    <el-dialog :visible.sync="spuDialogFormVisible" :custom-class="spuDialogClass" title="商品选择">
      <template>
        <div class="app-container" style="padding-bottom: 0;padding-top: 0;">
          <!-- 查询和其他操作 -->
          <div class="filter-container">
            <!-- <el-cascader :options="categoryOptions" :props="{ checkStrictly: true }" placeholder="请选择类目" clearable class="filter-item" filterable style="width: 200px;" @change="handleCategoryOption" /> -->
            <el-input
              v-model="listSpuQuery.search"
              clearable
              class="filter-item"
              style="width: 200px;"
              placeholder="输入名称"
            />
            <el-button
              class="filter-item"
              type="primary"
              icon="el-icon-search"
              @click="handleSpuFilter"
            >查找</el-button>
          </div>

          <!-- 查询结果 -->
          <el-table
            v-loading="listSpuLoading"
            ref="spuTable"
            :data="spuList"
            :row-key="getRowKey"
            size="small"
            element-loading-text="正在查询中。。。"
            border
            fit
            highlight-current-row
            style="white-space: pre-line"
            max-height="400"
            @selection-change="selectChange"
          >
            <el-table-column
              :reserve-selection="false"
              :selectable="ifCanSelectSpu"
              align="center"
              type="selection"
              width="55"/>
            <el-table-column v-if="hidden" prop="spuName"/>
            <el-table-column v-if="hidden" prop="skuName"/>
            <el-table-column v-if="hidden" prop="skuId"/>
            <el-table-column v-if="hidden" prop="spuId"/>
            <el-table-column prop="goodsName" align="center" label="商品名称" width="180px">
              <template slot-scope="scope">
                <el-col :span="6"><img :src="scope.row.img + '?x-oss-process=style/100px'" width="40" ></el-col>
                <el-col :span="18" style="padding-top: 15px;">{{ scope.row.spuName + '' +scope.row.skuName }}</el-col>
              </template>
            </el-table-column>
            <el-table-column prop="unit" align="center" label="单位"/>
            <el-table-column prop="barCode" align="center" label="条形码"/>
            <el-table-column prop="warehouseSkuNum" align="center" label="可用库存"/>
            <el-table-column prop="averPrice" align="center" label="平均成本"/>
          </el-table>
          <pagination
            v-show="spuListTotal>0"
            :total="spuListTotal"
            :page.sync="listSpuQuery.pageNo"
            :limit.sync="listSpuQuery.limit"
            :pager-count="5"
            layout="prev, pager, next"
            style="padding-bottom: 0;padding-top: 0;"
            @pagination="listGoods"
          />
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="spuDialogFormVisible=false">取消</el-button>
          <el-button type="primary" @click="saveStoreSpu">保存</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<style>
.el-table .cell {
  white-space: pre-line;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
.el-date-editor .el-range-separator{
  width: 10%;
}
</style>

<script>
import { exportSkuSummary } from '@/api/storeSummary'
import { create, page, update, audit, listStoreSkuByOrderId, pageSkusBySupplierIdWithPrice } from '@/api/purchasereturnorder'
import { formatDateAndTime } from '@/filters'
import { listSuppliersByPara } from '@/api/supplier'
import { listWareHousesByPara } from '@/api/warehouse'
import { categorySecondLevelTree, categoryTree } from '@/api/category'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
const extraStatusMap = {
  '0': '待审核',
  '1': '已通过',
  '2': '驳回'
}
export default {
  name: 'SupplierPurchaseReturnOrder',
  components: { Pagination },
  filters: {
    formatGmt(time) {
      if (time == null || time === '') {
        return ''
      }
      return formatDateAndTime(time)
    },
    formatOrderState(state) {
      switch (state) {
        case 0 :
          return '待审核'
        case 1 :
          return '已通过'
        case 2 :
          return '驳回'
        default :
          return ''
      }
    }
  },
  data() {
    return {
      extraStatusMap,
      statusMap: [{ value: 0, name: '待审核' }, { value: 1, name: '已通过' }, { value: 2, name: '驳回' }],
      list: undefined,
      total: 0,
      storeId: undefined,
      listLoading: true,
      listQuery: {
        pageNo: 1,
        limit: 20,
        status: undefined,
        timeInfo: undefined,
        customerType: 1
      },
      timeInfo: undefined,
      options: [],
      supplierList: [],
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        storeOrderInsertTime: [
          { required: true, message: '请选择时间', trigger: 'blur' }
        ],
        warehouseId: [
          { required: true, message: '请选择仓库', trigger: 'blur' }
        ],
        supplierId: [
          { required: true, message: '请选择供应商', trigger: 'blur' }
        ]
      },
      dataForm: {
        id: undefined,
        warehouseId: undefined,
        warehouseIsSelected: true,
        customerType: 1,
        supplierId: undefined
      },
      auditDataForm: {
        orderId: undefined
      },
      commentShow: false,
      auditDialogVisible: false,
      auditFormLoading: true,
      dialogFormVisible: false,
      spuDialogFormVisible: false,
      hidden: false,
      listSpuQuery: {
        pageNo: 1,
        limit: 20,
        search: '',
        categoryIds: '',
        categorySecondIds: '',
        warehouseId: undefined
      },
      optloading: false,
      warehouseList: [],
      selectSpuList: [],
      spuList: [],
      selectGoodList: [],
      categoryOptions: [],
      listSpuLoading: true,
      optDiaLogWidth: '80%',
      spuDialogClass: 'spuDialogClass',
      spuListTotal: 0,
      goodsNumPatternValid: true,
      goodsNumlimitValid: true,
      goodsPricePatternValid: true,
      goodsPriceLimitValid: true
    }
  },
  computed: {
    selSpuListTotal: function() {
      let total = 0
      if (this.selectSpuList.length) {
        for (let i = 0; i < this.selectSpuList.length; i++) {
          if (this.selectSpuList[i].goodsReturnNum && new RegExp('^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,3})?$').test(this.selectSpuList[i].goodsReturnNum)) {
            total += parseFloat(this.selectSpuList[i].goodsReturnNum)
          }
        }
      }
      return total.toFixed(2)
    },
    selSpuListTotalPrice: function() {
      let totalPrice = 0
      for (let i = 0; i < this.selectSpuList.length; i++) {
        if (this.selectSpuList[i].goodsPrice && new RegExp('^[0-9]+(.[0-9]{1,2})?$').test(this.selectSpuList[i].goodsPrice) && this.selectSpuList[i].goodsReturnNum && new RegExp('^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,3})?$').test(this.selectSpuList[i].goodsReturnNum)) {
          totalPrice += this.selectSpuList[i].goodsPrice * this.selectSpuList[i].goodsReturnNum
        }
      }
      return totalPrice.toFixed(2)
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      page(this.listQuery)
        .then(response => {
          this.list = response.data.data.items
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      const timeInfos = []
      if (this.timeInfo && this.timeInfo !== '') {
        if (this.timeInfo.indexOf(',') === -1) {
          timeInfos.push(this.timeInfo[0] + ' 00:00:00')
          timeInfos.push(this.timeInfo[1] + ' 23:59:59')
        }
      }
      this.listQuery.timeRange = timeInfos.join(',')
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        id: undefined,
        warehouseId: undefined,
        warehouseIsSelected: true,
        supplierId: undefined,
        customerType: 1
      }
    },
    handleCreate() {
      this.resetForm()
      this.listWarehouses()
      this.listSuppliersByPara()
      this.dialogStatus = 'create'
      this.selectSpuList = []
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData(status) {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const selectSpuList = this.selectSpuList
          let isHasEmptyValue = false
          for (let i = 0; i < selectSpuList.length; i++) {
            if (!selectSpuList[i].goodsReturnNum) {
              isHasEmptyValue = true
              break
            }
            if (!new RegExp('^[0-9]+(.[0-9]{1,3})?$').test(selectSpuList[i].goodsReturnNum)) {
              this.goodsNumPatternValid = false
              break
            }
            if (!new RegExp('^[0-9]+(.[0-9]{1,2})?$').test(selectSpuList[i].goodsPrice)) {
              this.goodsPricePatternValid = false
              break
            }
          }
          if (selectSpuList.length === 0) {
            this.$notify.error({
              title: '失败',
              message: '请选择退货商品'
            })
          } else if (isHasEmptyValue) {
            this.$notify.error({
              title: '失败',
              message: '请核对退货商品数量'
            })
          } else if (!this.goodsNumPatternValid) {
            this.$notify({
              title: '提示',
              message: '数量请填写最多三位小数的数字',
              type: 'warning'
            })
          } else if (!this.goodsPricePatternValid) {
            this.$notify({
              title: '提示',
              message: '单价请填写最多2位小数的数字',
              type: 'warning'
            })
          } else {
            this.dataForm.purchaseOrderReturnGoods = this.selectSpuList
            this.dataForm.orderReturnAmount = this.selSpuListTotalPrice
            this.dataForm.orderGoodsReturnCount = this.selSpuListTotal
            this.dataForm.customerId = this.dataForm.supplierId
            this.optloading = true
            create(this.dataForm)
              .then(response => {
                this.optloading = false
                this.dialogFormVisible = false
                this.$notify.success({
                  title: '成功',
                  message: '创建成功'
                })
                this.getList()
              })
              .catch(response => {
                this.optloading = false
                this.$notify.error({
                  title: '失败',
                  message: '失败'
                })
              })
          }
        }
      })
    },
    updateData(status) {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const selectSpuList = this.selectSpuList
          let isHasEmptyValue = false
          for (let i = 0; i < selectSpuList.length; i++) {
            if (!selectSpuList[i].goodsReturnNum) {
              isHasEmptyValue = true
              break
            }
            if (!new RegExp('^[0-9]+(.[0-9]{1,3})?$').test(selectSpuList[i].goodsReturnNum)) {
              this.goodsNumPatternValid = false
              break
            }
            if (!new RegExp('^[0-9]+(.[0-9]{1,2})?$').test(selectSpuList[i].goodsPrice)) {
              this.goodsPricePatternValid = false
              break
            }
          }
          if (selectSpuList.length === 0) {
            this.$notify.error({
              title: '失败',
              message: '请选择退货商品'
            })
          } else if (isHasEmptyValue) {
            this.$notify.error({
              title: '失败',
              message: '请核对退货商品数量'
            })
          } else if (!this.goodsNumPatternValid) {
            this.$notify({
              title: '提示',
              message: '数量请填写最多三位小数的数字',
              type: 'warning'
            })
          } else if (!this.goodsPricePatternValid) {
            this.$notify({
              title: '提示',
              message: '单价请填写最多2位小数的数字',
              type: 'warning'
            })
          } else {
            this.dataForm.purchaseOrderReturnGoods = this.selectSpuList
            this.dataForm.orderReturnAmount = this.selSpuListTotalPrice
            this.dataForm.orderGoodsReturnCount = this.selSpuListTotal
            this.optloading = true
            update(this.dataForm)
              .then(response => {
                this.optloading = false
                this.getList()
                this.dialogFormVisible = false
                this.$notify.success({
                  title: '成功',
                  message: '更新成功'
                })
              })
              .catch(response => {
                this.optloading = false
                this.$notify.error({
                  title: '失败',
                  message: '失败'
                })
              })
          }
        }
      })
    },
    handleUpdate(row) {
      this.listWarehouses()
      this.listSuppliersByPara()
      this.dataForm = Object.assign({}, row)
      this.listStoreSkuByOrderId(row.id)
      this.dataForm.supplierId = row.customerId
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDetail(row) {
      this.$router.push({ path: '/storereturnorder/detail?pOrderId=' + row.id })
    },
    handleSpuFilter() {
      this.listSpuQuery.pageNo = 1
      this.listGoods()
    },
    handleSkuAdd() {
      this.spuDialogFormVisible = true
      this.categoryOptions = []
      this.categorySecondLevelTree()
      this.refreshCategoryOptions()
      this.listSpuQuery.warehouseId = this.dataForm.warehouseId
      this.listSpuQuery.supplierId = this.dataForm.supplierId
      this.listSpuQuery.customerType = this.dataForm.customerType
      this.listGoods()
    },
    listGoods() {
      this.listSpuLoading = true
      pageSkusBySupplierIdWithPrice(this.listSpuQuery)
        .then(response => {
          this.spuList = response.data.data.items
          this.spuListTotal = response.data.data.total
          this.listSpuLoading = false
        })
        .catch(() => {
          this.spuList = []
          this.listSpuLoading = false
        })
    },
    categorySecondLevelTree() {
      categorySecondLevelTree()
        .then(response => {
          this.categoryList = response.data.data
        })
        .catch(() => {
          this.categoryList = []
        })
    },
    handleCategoryOption(e) {
      if (e !== undefined) {
        const tag = e[e.length - 1]
        this.listSpuQuery.categoryIds = tag // 回调指定分类
      } else {
        this.listSpuQuery.categoryIds = undefined
      }
    },
    refreshCategoryOptions() {
      if (this.categoryOptions.length === 0) {
        categoryTree().then(response => {
          this.categoryOptions = response.data.data
        })
      }
    },
    saveStoreSpu() {
      const selection = this.selectGoodList
      this.spuDialogFormVisible = false
      this.selectSpuList = selection
    },
    getRowKey(row) {
      return row.skuId
    },
    selectChange(selection) {
      this.selectGoodList = selection
    },
    goodsBuyNumLimit(row) {
      const that = this
      const flag = new RegExp('^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,3})?$').test(row.goodsReturnNum)
      if (!flag) {
        this.$notify({
          title: '提示',
          message: '数量请填写最多三位小数的数字',
          type: 'warning'
        })
        this.$set(row, 'goodsReturnNum', '')
        that.goodsNumPatternValid = false
        that.goodsNumlimitValid = true
      } else {
        that.goodsNumPatternValid = true
        if (row.goodsReturnNum && row.warehouseSkuNum < row.goodsReturnNum) {
          this.$notify({
            title: '提示',
            message: '数量不能大于可用库存',
            type: 'warning'
          })
          this.$set(row, 'goodsReturnNum', '')
          that.goodsNumlimitValid = false
        }
      }
    },
    goodsPriceLimit(row) {
      const that = this
      const flag = new RegExp('^[0-9]+(.[0-9]{1,2})?$').test(row.goodsPrice)
      if (!flag) {
        this.$notify({
          title: '提示',
          message: '数量请填写最多2位小数的数字',
          type: 'warning'
        })
        this.$set(row, 'goodsPrice', '')
        that.goodsPricePatternValid = false
        that.goodsPriceLimitValid = true
      } else {
        that.goodsPricePatternValid = true
        if (row.averPrice && row.averPrice < row.goodsPrice) {
          this.$notify({
            title: '提示',
            message: '数量不能大于平均成本',
            type: 'warning'
          })
          this.$set(row, 'goodsPrice', '')
          that.goodsPriceLimitValid = false
        }
      }
    },
    removeSpu(skuId) {
      for (let i = 0; i < this.selectSpuList.length; i++) {
        if (this.selectSpuList[i].skuId === skuId) {
          this.selectSpuList.splice(i, 1)
          break
        }
      }
      if (this.selectSpuList) {
        this.selectSpuList.forEach(row => {
          this.$refs.spuTable.toggleRowSelection(row)
        })
      }
    },
    listStoreSkuByOrderId(orderId) {
      this.listSpuQuery.status = 1
      this.listSpuQuery.orderId = orderId
      listStoreSkuByOrderId(this.listSpuQuery)
        .then(response => {
          this.selectSpuList = response.data.data
        })
        .catch(() => {
          this.selectSpuList = []
        })
      this.listSpuQuery.orderId = undefined
    },
    handleAudit(row) {
      this.auditDialogVisible = true
      this.auditDataForm = {
        auditComment: '',
        orderState: '1',
        orderId: row.id
      }
    },
    auditOrder() {
      if (this.auditDataForm.orderState === '2') {
        if (this.auditDataForm.auditComment === '' || this.auditDataForm.auditComment.trim() === '') {
          this.$notify.info({
            title: '系统提示',
            message: '请填写驳回意见'
          })
          return
        }
      }
      this.auditFormLoading = true
      audit(this.auditDataForm)
        .then(response => {
          this.auditFormLoading = false
          this.auditDialogVisible = false
          this.$notify.success({
            title: '成功',
            message: '审核成功'
          })
          this.getList()
        })
        .catch(response => {
          this.auditFormLoading = false
          this.$notify.error({
            title: '失败',
            message: '失败'
          })
        })
    },
    changeOrderState() {
      const comment = this.auditDataForm.comment
      this.auditDataForm.comment = this.auditDataForm.state === '1' ? '' : comment
    },
    handleConfirm(row) {
      this.$confirm('确认之后，门店商品数量会相应增加！', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(({ value }) => {
        this.auditDataForm.orderId = row.id
        this.confirmOrder()
      })
      this.auditDataForm.id = undefined
    },
    ifCanSelectSpu(row, index) {
      return row.warehouseSkuNum > 0
    },
    listWarehouses() {
      const that = this
      listWareHousesByPara({ status: 1 })
        .then(response => {
          this.warehouseList = response.data.data
        })
        .catch(() => {
          this.warehouseList = []
          that.dataForm.warehouseId = undefined
        })
    },
    ifCanSelSpu() {
      this.dataForm.warehouseIsSelected = true
      if (this.dataForm.warehouseId && this.dataForm.supplierId) {
        this.dataForm.warehouseIsSelected = false
      }
    },
    skuSummary() {
      let startTime = ''
      let endTime = ''
      if (!this.timeInfo) {
        this.$notify.info({
          title: '系统提示',
          message: '请选择导出时间范围'
        })
        return
      }
      if (this.timeInfo && this.timeInfo !== '') {
        if (this.timeInfo.indexOf(',') === -1) {
          startTime = this.timeInfo[0] + ' 00:00:00'
          endTime = this.timeInfo[1] + ' 23:59:59'
        }
      }
      exportSkuSummary(startTime, endTime, this.storeId, this.listQuery.storeOrderState, extraStatusMap[this.listQuery.storeOrderState], this.listQuery.search, 21, '退货汇总')
    },
    listSuppliersByPara() {
      this.listQuery.status = 1
      listSuppliersByPara(this.listQuery)
        .then(response => {
          this.supplierList = response.data.data
        })
        .catch(() => {
          this.supplierList = []
        })
    }
  }
}
</script>
